package com.zhidisoft.Task.springmvccontroller;

import com.zhidisoft.manage.dao.IndustryDao;
import com.zhidisoft.manage.dao.TaxOrganDao;
import com.zhidisoft.manage.dao.TaxPayerDao;
import com.zhidisoft.manage.dao.TaxSourceDao;
import com.zhidisoft.manage.entity.TaxPayer;
import com.zhidisoft.manage.entity.TaxSource;
import com.zhidisoft.system.dao.TaxerDao;
import com.zhidisoft.system.dao.UserDao;
import com.zhidisoft.system.entity.User;
import com.zhidisoft.util.FormatDate;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class TaskSpringMvc {
    /**
     * 到搜索页面
     *
     * @return
     */
    @RequestMapping("/toSearchTask.do")
    public String toSearchTask() {
        return "searchTask";
    }

    /**
     * 展示任务
     *
     * @param page
     * @param rows
     * @param payerCode
     * @param payerName
     * @param subOrganId
     * @param startDate
     * @param endDate
     * @param industryId
     * @return
     */
    @RequestMapping("/searchTask.do")
    @ResponseBody
    public ModelMap searchTask(String page, String rows, String payerCode, String payerName, String subOrganId,
                               String startDate, String endDate, String industryId) {
        int pageNum = 1;
        if (page != null && !page.isEmpty()) {
            pageNum = Integer.parseInt(page);
        }
        int pageSize = 10;
        if (rows != null && !rows.isEmpty()) {
            pageSize = Integer.parseInt(rows);
        }
        Map<String, String> params = new HashMap<>();
        params.put("payerCode", payerCode);
        params.put("payerName", payerName);

        if ("-1".equals(subOrganId)) {
            params.put("subOrganId", null);
        } else {
            params.put("subOrganId", subOrganId);
        }

        params.put("startDate", startDate);

        params.put("endDate", endDate);

        if ("-1".equals(industryId)) {
            params.put("industryId", null);
        } else {
            params.put("industryId", industryId);
        }
        List<Map<String, String>> result = TaxSourceDao.getSearchTasks(pageNum,
                pageSize, params);
        JSONArray jsonArray = new JSONArray();
        // 获得查询map集合，计算时间差（可以再sql语句中直接获取）
        for (Map<String, String> map : result) {
            String timeOut = FormatDate.getTimeOut(map.get("executeTime"),
                    map.get("recordTaskDate"));
            map.put("timeOut", timeOut);
            jsonArray.add(map);
        }
        int totalRows = TaxSourceDao.getSearchRows(params);
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("total", totalRows);
        modelMap.addAttribute("rows", jsonArray);
        return modelMap;
    }

    /**
     * 获取任务信息
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/getTaskInfo.do")
    public String getTaskInfo(Model model, String id) {
        TaxSource task = TaxSourceDao.getTask(Integer.parseInt(id));
        TaxPayer payer = TaxPayerDao.getPayer(task.getPayerId().toString());
        model.addAttribute("task", task);
        model.addAttribute("payer", payer);
        model.addAttribute("organ", TaxOrganDao.getOrgan(payer.getTaxOrganId()));
        model.addAttribute("industry", IndustryDao.getIndustry(payer.getIndustryId()));
        model.addAttribute("subOrgan", TaxOrganDao.getOrgan(task.getSubOrganId()));
        model.addAttribute("user", UserDao.getUserById(payer.getUserId()));
        model.addAttribute("executeTaxer", TaxerDao.getTaxerById(task.getExecuteId()));
        model.addAttribute("approverTaxer", TaxerDao.getTaxerById(task.getRecordUserId()));
        model.addAttribute("taskUser", UserDao.getUserById(task.getRecordUserId()));

        return "taskInfo";

    }

    /**
     * 删除任务
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteTask.do")
    @ResponseBody
    public ModelMap deleteTask(String id) {
        ModelMap modelMap = new ModelMap();
        JSONObject json = new JSONObject();
        boolean b = TaxSourceDao.deleteTask(id);
        if (b) {
            modelMap.put("success", true);
            modelMap.put("msg", "删除成功");
        } else {
            modelMap.put("success", false);
            modelMap.put("msg", "删除失败");
        }
        return modelMap;

    }

    /**
     * 到修改任务页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/toEditTask.do")
    public String toEditTask(String id, Model model) {
        TaxSource task = TaxSourceDao.getTask(Integer.parseInt(id));
        TaxPayer payer = TaxPayerDao.getPayer(task.getPayerId().toString());
        model.addAttribute("task", task);
        model.addAttribute("payer", payer);
        model.addAttribute("organ", TaxOrganDao.getOrgan(payer.getTaxOrganId()));
        model.addAttribute("industry", IndustryDao.getIndustry(payer.getIndustryId()));
        model.addAttribute("subOrgan", TaxOrganDao.getOrgan(task.getSubOrganId()));//下达部门
        model.addAttribute("user", UserDao.getUserById(payer.getUserId()));
        model.addAttribute("executeTaxer", TaxerDao.getTaxerById(task.getExecuteId()));    //执行人
        model.addAttribute("approverTaxer", TaxerDao.getTaxerById(task.getApproverId()));//批准人
//		req.setAttribute("taskUser",
//				UserDao.getUserById(task.getRecordUserId()));
        model.addAttribute("taxers", TaxerDao.getTaxers());//所有人
        model.addAttribute("organs", TaxOrganDao.getOrgans());
        return "editTask";
    }

    /**
     * 修改任务
     *
     * @return
     */
    @RequestMapping("/editTask.do")
    @ResponseBody
    public ModelMap editTask(HttpSession session, String id, String payerId, String taskName, String approverId, String executeId, String executeTime,
                             String taskState, String idea, String riskLevel, String subOrganId) {
        TaxSource task = new TaxSource();
        if (id != null) {
            task.setId(Integer.valueOf(id));//NumberFormatException
        }

        if (payerId == null || payerId.length() == 0) {
            task.setPayerId(null);
        } else {
            task.setPayerId(Integer.valueOf(payerId));
        }

        task.setTaskName(taskName);

        if ("-1".equals(subOrganId)) {
            task.setSubOrganId(null);
        } else if (subOrganId != null) {
            task.setSubOrganId(Integer.parseInt(subOrganId));
        }

        if ("-1".equals(approverId)) {
            task.setApproverId(null);
        } else if (approverId != null) {
            task.setApproverId(Integer.valueOf(approverId));
        }

        if ("-1".equals(executeId)) {
            task.setExecuteId(null);
        } else if (executeId != null) {
            task.setExecuteId(Integer.valueOf(executeId));
        }

        task.setExecuteTime(executeTime);

        task.setTaskState(taskState);

        task.setIdea(idea);

        if (riskLevel != null) {
            task.setRiskLevel(Integer.valueOf(riskLevel));
        }
        User user = (User) session.getAttribute("user");
        if (user != null) {
            Integer recordUserId = user.getId();
            task.setRecordUserId(recordUserId);
        }
        Date date = new Date();
        task.setRecordTaskDate(FormatDate.format(date));
        ModelMap modelMap = new ModelMap();
        boolean b = TaxSourceDao.edit(task, Integer.parseInt(id));
        if (b) {
            modelMap.put("success", true);
            modelMap.put("msg", "修改任务成功");
        } else {
            modelMap.put("success", false);
            modelMap.put("msg", "修改失败");
        }

        return modelMap;
    }

    /**
     * 跳转未被统计企业
     *
     * @return
     */
    @RequestMapping("/toStatistical.do")
    public String statistical() {
        return "statistical";
    }

    /**
     * 获取未被调查企业
     *
     * @param page
     * @param rows
     * @param payerName
     * @param payerCode
     * @return
     */
    @RequestMapping("/getStatistical.do")
    @ResponseBody
    public ModelMap getStatistical(String page, String rows, String payerName, String payerCode) {
        ModelMap modelMap = new ModelMap();
        int pageNum = 1;
        if (page != null && !page.isEmpty()) {
            pageNum = Integer.parseInt(page);
        }
        int pageSize = 10;
        if (rows != null && !rows.isEmpty()) {
            pageSize = Integer.parseInt(rows);
        }
        TaxPayerDao tpd = new TaxPayerDao();
        int totalRows = tpd.getTotalRows();

        //传递参数
        modelMap.put("total", totalRows);
        List<Map<String, String>> result = TaxPayerDao.getStatistical(pageNum, pageSize, payerCode, payerName);
        JSONArray jsonArray = new JSONArray();
        for (Map map : result) {
            jsonArray.add(map);
        }
        modelMap.addAttribute("rows", jsonArray);

        return modelMap;
    }
}
